<script setup lang="ts">
import { useLocalStorage } from '@peng_kai/kit/libs/vueuse';
import { ApiError } from '@peng_kai/kit/request';
import { InputPassword } from '~comp/input';
import Turnstile, { cfRules } from '~comp/Turnstile.vue';
import { gsap } from 'gsap';
import { noticeMeta } from '~/composables/useMeta';
import { flzxsqc } from '~/utils';
import { jsBridge } from '~/utils/defines';
import { getInvitationCode, validatePassword } from '../helpers';
import { useFirstTimeRewardsState } from '../hooks';
import bonusSvg from './imgs/bonus.svg';

const props = defineProps<{ onToSignIn?: () => void; onFulfilled?: () => void }>();
const router = useRouter();
const defaultReferralCode = getInvitationCode();
const invitedSinpStorage = useLocalStorage('invitedSpin', { jump: false, firstDraw: false });
const turnstileDomRef = ref();

const showReferralCode = ref(false);

const form = useAntdForm({
  email: {
    value: '',
    rules: [{ required: true, type: 'email', message: $t('aw95tLwTkGmrgSVCHW') }],
  },
  password: {
    value: '',
    rules: [{ validator: validatePassword }],
  },
  referral_code: {
    value: defaultReferralCode,
  },
  cf_turnstile_response: {
    value: '',
    rules: cfRules,
  },
  is_agreement: {
    value: true,
    rules: [{ validator: (_, v) => v ? formResult() : formResult($t('ywffgOzz2yce3hBpSw8d')) }],
  },
});

const registerMut = useMutation({
  mutationKey: [apis.apiAuthRegister.id],
  mutationFn: apis.apiAuthRegister.setDefaultConfig({ errorMessage: false }),
  onSuccess(res) {
    noticeMeta().register({ plateform: 'account', id: res.uid });
    jsBridge.post('register', { uid: res.uid, email: res.email, referralCode: res.referral_code });
    props.onFulfilled?.();
    if (!invitedSinpStorage.value.jump && invitedSinpStorage.value.firstDraw) {
      router.push({ name: RN.INVITATION });
    }
  },
  onError(e, payload) {
    const isApiError = e instanceof ApiError;
    const body = payload.requestBody!;

    if (isApiError && e.code === 15024) {
      antdMessage.success($t('3uiu_6WEzGyEm1YbbT15g'));
      props.onFulfilled?.();
      globalPopups.verifyEmail.open({ type: 1, email: body.email });
    }
    else {
      antdMessage.error(e.message);
    }
    turnstileDomRef.value?.reset?.();
    form.$form?.clearValidate?.();
  },
});

const getIsLoadingRef = computed(() => registerMut.isPending.value);

function submit() {
  const requestBody = {
    ...form.state,
    password: flzxsqc(form.state.password),
    password_confirm: flzxsqc(form.state.password),
    is_luckyspin: useFirstTimeRewardsState(),
  };
  jsBridge.post('registerClick', { email: requestBody.email, referralCode: requestBody.referral_code });
  registerMut.mutateAsync({ requestBody });
}

onMounted(() => {
  const tl = gsap.timeline({ repeat: -1, repeatDelay: 0 });
  tl.to('.gift-icon-scoped', { rotation: -8, duration: 0.4, ease: 'power2.inOut' })
    .to('.gift-icon-scoped', { rotation: 8, duration: 0.4, ease: 'power2.inOut' });
});
</script>

<template>
  <div>
    <AForm v-bind="form.props" class="ant-cover__Form-compact" :disabled="getIsLoadingRef" @finish="submit()">
      <TAntdTheme component="Input" theme="light">
        <AFormItem v-bind="form.itemProps.email">
          <AInput v-model:value="form.state.email" :placeholder="$t('hVaEobWzd70kjGP9Awnt')">
            <template #prefix>
              <i class="i-ri:mail-fill mr-1 text-1.2em text-sys-text-body" />
            </template>
          </AInput>
        </AFormItem>

        <AFormItem v-bind="form.itemProps.password">
          <InputPassword v-model:value="form.state.password" :placeholder="$t('j0xjWyPV3Op0WcKas3Ke')" />
        </AFormItem>

        <div v-if="!defaultReferralCode" class="grid grid-cols-1 mb-3.5 gap-2">
          <div class="flex cursor-pointer items-center gap-0.5 text-sys-text-body" @click="showReferralCode = !showReferralCode">
            <div>{{ $t('kS728r29INmVheKz7Rre') }}</div>
            <i v-if="showReferralCode" class="i-mingcute:up-line h-4.5 w-4.5 cursor-pointer text-4.5 font-semibold" />
            <i v-else class="i-mingcute:down-line h-4.5 w-4.5 cursor-pointer text-4.5 font-semibold" />
          </div>
          <AFormItem v-if="showReferralCode" v-bind="form.itemProps.referral_code" class="!mb-0">
            <AInput v-model:value="form.state.referral_code" :placeholder="$t('eFeyAkUrmRzHyqHtXxRnj')">
              <template #prefix>
                <i class="i-mingcute:invite-fill mr-1 text-1.2em text-sys-text-body" />
              </template>
            </AInput>
          </AFormItem>
        </div>

        <AFormItem v-bind="form.itemProps.cf_turnstile_response">
          <Turnstile ref="turnstileDomRef" v-model:value="form.state.cf_turnstile_response" />
        </AFormItem>
      </TAntdTheme>

      <AFormItem v-bind="form.itemProps.is_agreement">
        <ACheckbox v-model:checked="form.state.is_agreement">
          <I18nT keypath="gl747HIsjIgzDDpx1sItB" tag="spab" class="text-sys-text-body">
            <template #link>
              <RouterLink :to="{ name: RN.HELP_PRIVACY_POLICY }">
                <span class="cursor-pointer url-yellow-underline">{{ $t('gaYa7jhqaBxg8ToJwVnn') }}</span>
              </RouterLink>
            </template>
          </I18nT>
        </ACheckbox>
      </AFormItem>
      <div class="relative w-full flex flex-col items-center justify-center">
        <div class="tip-container-bg relative z-1">
          <img :src="bonusSvg" class="gift-icon-scoped w-7.5">
          <div class="ml-1.5 text-sm text-sys-text-head font-bold">
            150% Bonus
          </div>
        </div>
        <svg class="!-mt-1" xmlns="http://www.w3.org/2000/svg" width="14" height="10" viewBox="0 0 14 10" fill="none">
          <path d="M6.66667 10L12.4402 2.5H0.893164L6.66667 10Z" fill="#EAB308" />
        </svg>
      </div>
      <AButton
        class="ant-cover__Button-3d-primary mt-3 w-full"
        type="primary"
        htmlType="submit"
        :loading="getIsLoadingRef"
        :disabled="getIsLoadingRef"
      >
        {{ $t('wV2h5ZuzGb9WHcTjDAaGx') }}
      </AButton>
    </AForm>

    <div class="my-2 text-center">
      {{ $t('iUd6Zdwwr45CQpJsCatS') }} <span class="cursor-pointer url-yellow-underline" @click="props.onToSignIn">{{ $t('qwZi820O3qWpsae62Juc') }}</span>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.tip-container-bg {
  --uno: 'flex items-center justify-center border-(1.5px yellow-500 solid) rounded-full px-5 py-2';
  background: radial-gradient(84.02% 123.6% at 16.73% -9.06%, rgba(234, 179, 8, 0.2) 0%, rgba(19, 20, 22, 0.2) 68.89%),
    var(--sys-layer-d, #26272e);
  box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.5);
}
</style>
